from rest_framework.response import Response
from .models import User
from rest_framework import serializers
import re
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
from celery_tasks.email.tasks import send_verify_email
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from django.conf import settings

class UserSerizlizer(serializers.ModelSerializer):
    password2 = serializers.CharField(max_length=20,min_length=8,write_only=True)
    sms_code = serializers.CharField(max_length=6,min_length=6,write_only=True)
    allow = serializers.CharField(write_only=True)
    token = serializers.CharField(read_only=True,label="登录状态token")
    class Meta:
        model = User
        fields = ['id','username','password','mobile','password2','sms_code','allow','token']
        extra_kwargs = {
            'username':{
                'max_length':20,
                'min_length':8,
                'error_messages':{
                    "max_length":"用户名过长",
                    "min_length":"用户名过短",
                }
            },
            'password': {
                'write_only':True,
                'max_length': 20,
                'min_length': 8,
                'error_messages': {
                    "max_length": "密码过长",
                    "min_length": "密码过短",
                }
            },
        }


    # 其他网址在域名允许的情况知道后端端口下能访问后端

    # 判断手机号格式
    def validate_mobile(self,value):
        if not re.match(r'[1][13579]\d{9}$',value):
            #在视图函数调用is_valid(raise_expection)给抛出错误
            raise serializers.ValidationError("手机号格式错误")
        return value

    # 判断是是否同意协议
    def validate_allow(self,value):
        if value != 'true':
            raise serializers.ValidationError("未选中协议")
        return value


    def validate(self,attrs):
        # 链接缓存
        conn = get_redis_connection('verify')
        # 获取短信验证码
        sms_code = conn.get("SMScode_%s"%attrs['mobile'])
        # 判断短信验证码是否过期
        if not sms_code:
            raise serializers.ValidationError("短信验证码过期")
        # 判断填入的短信验证码是否一致
        if sms_code.decode() != attrs['sms_code']:
            raise serializers.ValidationError('短信验证码输入错误')
        # 判断两次输入的密码是否一致
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError("两次密码不一致")

        return attrs

    #　视图函数调用save方法时默认调用此create方法
    def create(self,validated_data):
        validated_data.pop("password2")
        validated_data.pop("sms_code")
        validated_data.pop("allow")
        print(validated_data)


        # User.objects.create(validated_data)

        # 重新调用ModelSerializer父类super().方法
        user = super().create(validated_data)

        # 要添加数据到数据库才有这个对象能调用这个方法
        # set_password的方法是在模型类User父类AbstractUser里面的
        # set_password把传进去的参数加密后赋值给user.password字段
        user.set_password(validated_data['password'])
        user.save()

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 把用户对象jwt_payload_handler方法中，
        # 从用户对象提取到用户信息给载荷payload
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        # 实例对象保存实例属性
        user.token = token

        return user


class UserDetailSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id','email','mobile','username','email_active')




class UserEmailSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id','email']
        extra_kwargs = {
            'email':{
                'required':True,
            }
        }



    def update(self, instance, validated_data):
        # user = self.context['user']
        # user = validated_data['user']
        instance.email = validated_data['email']
        instance.save()

        # 做完保存操作后，接着发送邮件到

        tjs = TJS(settings.SECRET_KEY,300)
        # 　加密后是字节解码成字符串
        token = tjs.dumps({'id':instance.id,'username':instance.username}).decode()
        print(token)
        send_verify_email.delay(validated_data['email'],token)

        return instance



class VerifyEmailSerializer(serializers.Serializer):
    token = serializers.CharField(write_only=True)

    def validate(self, attrs):
        tjs = TJS(settings.SECRET_KEY, 300)
        try:
            data = tjs.loads(attrs['token'])
        except:
            raise serializers.ValidationError('错误的token')
        if not data:
            raise serializers.ValidationError('token已失效')
        attrs['data'] = data
        return attrs
    # def update(self, instance, validated_data):
    #     instance.email_active = True
    #     instance.save()
    #     return instance







